import 'dart:async';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_learn_vi/src/page/login/bofang_login_main_page.dart';
import 'package:flutter_learn_vi/src/page/login/login_model.dart';
import 'package:flutter_learn_vi/src/page/login/view/button_border_white_widget.dart';
import 'package:flutter_learn_vi/src/page/login/view/text_bottom_border_widget.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/11/22.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
/// 西瓜视频 https://www.ixigua.com/home/3662978423
/// 知乎 https://www.zhihu.com/people/zhao-long-90-89
///
///
/// 气泡背景的登录页面

void main() => runApp(
      MaterialApp(
        home: BofangLogin2Page(),
      ),
    );

class BofangLogin2Page extends StatefulWidget {
  final String userName;
  final String password;

  const BofangLogin2Page({Key key, this.userName, this.password})
      : super(key: key);

  @override
  _BofangLogin2PageState createState() => _BofangLogin2PageState();
}

class _BofangLogin2PageState extends State<BofangLogin2Page>
    with TickerProviderStateMixin, WidgetsBindingObserver, LoginModel {
  @override
  void initState() {
    super.initState();
    //添加监听
    WidgetsBinding.instance.addObserver(this);

    // _userNameController.text = "ceshi1";
    // _passwordController.text = "123456";
    if (widget.userName != null) {
      _userNameController.text = widget.userName;
      _passwordController.text = widget.password;
      ToastUtils.showToast("正在自动登录中");
      Future.delayed(Duration(milliseconds: 400), () {
        _submitLoginFunction();
      });
    }
  }

  @override
  void dispose() {
    //解绑
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  bool _showInputBg = false;

  //应用尺寸改变时回调
  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    /*
     *Frame是一次绘制过程，称其为一帧，
     * Flutter engine受显示器垂直同步信号"VSync"的驱使不断的触发绘制，
     *Flutter可以实现60fps（Frame Per-Second），
     * 就是指一秒钟可以触发60次重绘，FPS值越大，界面就越流畅。
     */
    WidgetsBinding.instance.addPostFrameCallback((_) {
      //注意，不要在此类回调中再触发新的Frame，这可以会导致循环刷新。
      setState(() {
        ///获取底部遮挡区域的高度
        double keyboderFlexHeight = MediaQuery.of(context).viewInsets.bottom;
        print("键盘的高度 keyboderFlexHeight $keyboderFlexHeight");
        if (MediaQuery.of(context).viewInsets.bottom == 0) {
          //关闭键盘 启动logo动画反向执行 0.0 -1.0
          // logo 布局区域显示出来
          setState(() {
            _showInputBg = false;
          });
        } else {
          //显示键盘 启动logo动画正向执行 1.0-0.0
          // logo布局区域缩放隐藏
          setState(() {
            _showInputBg = true;
          });
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,

      ///填充布局
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: Stack(
          children: [
            //第一部分 第一层 渐变背景
            buildBackground(),
            //第二部分 第二层 气泡
            // BubbleWidget(),
            //第三部分 高斯模糊
            buildBlureWidget(),
            //第五部分 输入框与按钮
            buildColumn(context),
            //第六部分 左上角的关闭按钮
            buildCloseButton(context)
          ],
        ),
      ),
    );
  }

  Positioned buildCloseButton(BuildContext context) {
    return Positioned(
      top: 44,
      left: 10,
      child: CloseButton(
        color: Colors.white,
        onPressed: () {
          NavigatorUtils.openPageByFade(
            context,
            BoFangLoginPage(),
            isReplace: true,
          );
        },
      ),
    );
  }

  Widget buildHeroLogo(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Hero(
          tag: "loginTag",
          child: Material(
            color: Colors.transparent,
            child: ClipOval(
              child: InkWell(
                onTap: () {
                  Navigator.of(context).pop();
                },
                child: Image.asset(
                  "assets/images/2.0x/app_icon.png",
                  fit: BoxFit.fill,
                  width: 44,
                  height: 44,
                ),
              ),
            ),
          ),
        ),
        SizedBox(
          width: 16,
        ),
        Text(
          '欢迎登录',
          textAlign: TextAlign.center,
          style: TextStyle(
            color: Colors.white,
            fontSize: 26.0,
            fontWeight: FontWeight.w600,
          ),
        ),
      ],
    );
  }

  //第一部分 第一层 渐变背景
  Widget buildBackground() {
    return Positioned.fill(
      child: Image.asset(
        "assets/images/2.0x/login_bg.webp",
        fit: BoxFit.fill,
      ),
    );
  }

  //第三部分 高斯模糊
  Widget buildBlureWidget() {
    return Positioned.fill(
      child: BackdropFilter(
        filter: ImageFilter.blur(sigmaX: 0.3, sigmaY: 0.3),
        child: Container(
          color: Colors.black.withOpacity(0.8),
        ),
      ),
    );
  }

  //文本输入框控制器
  TextEditingController _userNameController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();

  //焦点控制器
  FocusNode _userNameFocusNode = new FocusNode();
  FocusNode _passwordFocusNode = new FocusNode();
  bool _passwordIvi = true;
  StreamController<bool> _passwordStreamController = new StreamController();

  //第五部分 输入框与按钮
  Widget buildColumn(BuildContext context) {
    return Positioned.fill(
      child: GestureDetector(
        onTap: () {
          hidenKeyBoard();
        },
        child: Container(
          color:
              _showInputBg ? Colors.black.withOpacity(0.9) : Colors.transparent,
          padding: EdgeInsets.all(44),
          child: buildInputColumn(context),
        ),
      ),
    );
  }

  Widget buildInputColumn(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        //子Widget 底部对齐
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          SizedBox(
            height: 80,
          ),
          //第四部分 顶部的文字 logo 的Hero动画
          buildHeroLogo(context),
          SizedBox(
            height: 80,
          ),
          TextFieldBottomBorderWidget(
            labelText: "手机号",
            hintText: '请输入手机号',
            focusNode: _userNameFocusNode,
            controller: _userNameController,
            obscureText: false,
            prefixIconData: Icons.mail_outline,
            submit: (String value) {
              checkUserName(value);
              //焦点切换
              _userNameFocusNode.unfocus();
              FocusScope.of(context).requestFocus(_passwordFocusNode);
            },
          ),
          SizedBox(
            height: 10.0,
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              StreamBuilder(
                initialData: true,
                stream: _passwordStreamController.stream,
                builder:
                    (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
                  return TextFieldBottomBorderWidget(
                    labelText: "密码",
                    hintText: '请输入密码',
                    controller: _passwordController,
                    focusNode: _passwordFocusNode,
                    obscureText: snapshot.data,
                    prefixIconData: Icons.lock_outline,
                    suffixIconData:
                        snapshot.data ? Icons.visibility : Icons.visibility_off,
                    submit: (String value) {
                      checkPassword(value);
                      _submitLoginFunction();
                    },
                    onTap: () {
                      _passwordIvi = !_passwordIvi;
                      _passwordStreamController.add(_passwordIvi);
                    },
                  );
                },
              ),
              SizedBox(
                height: 10.0,
              ),
            ],
          ),
          SizedBox(
            height: 20.0,
          ),
          ButtonBorderWidget(
            heroTag: "loginButton",
            hasBorder: true,
            buttonLabel: '登 录',
            onTap: () {
              _submitLoginFunction();
            },
          ),
          Container(
            width: double.infinity,
            margin: EdgeInsets.only(top: 10),
            height: 60,
          ),
        ],
      ),
    );
  }

  ///登录
  void _submitLoginFunction() async {
    //隐藏键盘
    hidenKeyBoard();

    //获取用户输入的内容
    String userName = _userNameController.text.trim();
    String password = _passwordController.text.trim();
    //校验
    submit(userName, password, context);
  }

  void hidenKeyBoard() {
    //隐藏键盘
    SystemChannels.textInput.invokeMethod('TextInput.hide');
    _passwordFocusNode.unfocus();
    _userNameFocusNode.unfocus();
  }
}
